/**
 * Copyright (C) 2009 aileron.cc
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package cc.aileron.wsgi.request;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import cc.aileron.commons.utils.CastUtils;
import cc.aileron.wsgi.init.WsgiEnvironment;

import com.google.inject.Inject;
import com.google.inject.Singleton;

/**
 * 実装
 * 
 * @author Aileron
 */
@Singleton
public class WsgiRequestParameterFactoryImpl implements
    WsgiRequestParameterFactory
{
    /*
     * (非 Javadoc)
     * 
     * @see
     * cc.aileron.wsgi.request.WsgiRequestParameterFactory#create(javax.servlet
     * .http.HttpServletRequest)
     */
    public WsgiRequestParameter create(final HttpServletRequest request) throws FileUploadException
    {
        if (ServletFileUpload.isMultipartContent(request))
        {
            return new RequestMultipart(charConvert, upload, request);
        }
        return new RequestUrlencoded(charConvert, request);
    }

    /**
     * @param upload
     * @param environment
     */
    @Inject
    public WsgiRequestParameterFactoryImpl(
        final ServletFileUpload upload,
        final WsgiEnvironment environment)
    {
        this.upload = upload;

        final Charset encode = environment.getEncode();
        final Charset defaultEncode = Charset.forName("ISO-8859-1");
        this.charConvert = new CharConvert()
        {
            @Override
            public String convert(final String value)
            {
                return new String(value.getBytes(defaultEncode), encode);
            }
        };
    }

    /**
     * upload
     */
    private final ServletFileUpload upload;

    /**
     * charConvert
     */
    private final CharConvert charConvert;
}

/**
 * 文字列の文字コード変換
 * 
 * @author Aileron
 * 
 */
interface CharConvert
{
    /**
     * @param value
     * @return 変換後の文字列
     */
    String convert(String value);
}

class RequestMultipart implements WsgiRequestParameter
{
    @Override
    public Object get(final String name)
    {
        final FileItem item = parameter.get(name);
        if (item.isFormField())
        {
            final String val = item.getString();
            if (val == null)
            {
                throw new NullPointerException("request-parameter is null ["
                        + name + "]");
            }
            return charConvert.convert(item.getString());
        }
        return parameter.get(name);
    }

    @Override
    public List<String> getKeys()
    {
        return keys;
    }

    /**
     * constractor
     * 
     * @param charConvert
     * @param upload
     * @param request
     * @throws FileUploadException
     */
    public RequestMultipart(
        final CharConvert charConvert,
        final ServletFileUpload upload,
        final HttpServletRequest request) throws FileUploadException
    {
        this.charConvert = charConvert;
        this.keys = new ArrayList<String>();
        this.parameter = new HashMap<String, FileItem>();
        for (final FileItem item : CastUtils.<List<FileItem>> cast(upload.parseRequest(request)))
        {
            keys.add(item.getFieldName());
            parameter.put(item.getFieldName(),
                    item);
        }
    }

    private final CharConvert charConvert;

    /**
     * keys
     */
    private final List<String> keys;

    /**
     * parameter
     */
    private final HashMap<String, FileItem> parameter;
}

/**
 * 
 * application/x-www-form-urlencoded 形式の Formパラメータ
 * 
 * @author Aileron
 * 
 */
class RequestUrlencoded implements WsgiRequestParameter
{

    @Override
    public Object get(final String name)
    {
        final String val = request.getParameter(name);
        if (val == null)
        {
            throw new NullPointerException("request-parameter is null [" + name
                    + "]");
        }
        return charConvert.convert(val);
    }

    @Override
    public List<String> getKeys()
    {
        return keys;
    }

    /**
     * @return keys
     */
    private List<String> initKeys()
    {
        final ArrayList<String> localKeys = new ArrayList<String>();
        final Enumeration<?> enumeration = request.getParameterNames();
        while (enumeration.hasMoreElements())
        {
            localKeys.add(enumeration.nextElement()
                .toString());
        }
        return localKeys;
    }

    /**
     * constractor
     * 
     * @param charConvert
     * 
     * @param request
     */
    public RequestUrlencoded(
        final CharConvert charConvert,
        final HttpServletRequest request)
    {
        this.charConvert = charConvert;
        this.request = request;
        this.keys = initKeys();
    }

    private final CharConvert charConvert;

    /**
     * keys
     */
    private final List<String> keys;

    /**
     * REQUEST
     */
    private final HttpServletRequest request;
}